/*
 *   Copyright (c) 2010-2022, SIUFUNG
 */
package net.siufung.market.base.dept.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.siufung.core.model.enums.DeletedEnum;
import net.siufung.core.utils.StringPool;
import net.siufung.market.base.dept.api.IDeptUserApi;
import net.siufung.market.base.dept.mapper.IDeptMapper;
import net.siufung.market.base.dept.mapper.entity.Dept;
import net.siufung.market.base.dept.service.IDeptService;
import net.siufung.mybatis.base.BaseServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.io.Serializable;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 系统部门 数据服务实现
 *
 * @author 陈建峰
 * @since 2022-07-13 22:40:52
 */
@Slf4j
@AllArgsConstructor
@Service(value = "deptService")
@Transactional(rollbackFor = Exception.class)
public class DeptServiceImpl extends BaseServiceImpl<IDeptMapper, Dept> implements IDeptService {

    private final IDeptUserApi deptUserApi;

    @Override
    public boolean save(Dept entity) {
        entity.setId(IdUtil.getSnowflake().nextIdStr());
        if(Strings.isNullOrEmpty(entity.getDeptCode())){
            entity.setDeptCode(IdUtil.fastSimpleUUID());
        }
        if(StringPool.ZERO.equals(entity.getParentId())){
            entity.setLevel(1);
        } else {
            Dept parentDept = super.getBaseMapper().selectById(entity.getParentId());
            entity.setLevel(1 + parentDept.getLevel());
        }
        return super.save(entity);
    }

    @Override
    public boolean updateStatusById(Serializable id, DeletedEnum deletedEnum) {
        if(super.update(new LambdaUpdateWrapper<Dept>()
                .eq(Dept::getId, id)
                .set(Dept::getDeleted, deletedEnum.getValue()))){
            List<Dept> deptArrayList = Lists.newArrayList();
            getBaseMapper().getChildDeptList(deptArrayList, id);
            List<Serializable> deptIdList = deptArrayList.stream()
                    .map(Dept::getId).collect(Collectors.toList());
            if(!CollectionUtils.isEmpty(deptIdList)){
                super.update(new LambdaUpdateWrapper<Dept>()
                        .in(Dept::getId, deptIdList)
                        .set(Dept::getDeleted, deletedEnum.getValue()));
                if(Objects.nonNull(deptUserApi)){
                    deptUserApi.updateStatusByDeptIds(deptIdList, deletedEnum);
                }
            }
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }
}